package com.hfxt.controller;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfxt.entity.Role;
import com.hfxt.entity.User;
import com.hfxt.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.aspectj.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hfxt.service.RoleService;
import com.hfxt.service.UserService;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.management.relation.RelationSupport;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Api(value = "用户管理模块")
@RequestMapping("/user")
public class UserController {
    private final Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    //userListAll
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/getAllUserList", method = {RequestMethod.GET, RequestMethod.POST})
//    @RequestMapping(value = "/getAllUserList", method = RequestMethod.GET)
    public List<User> getAllUserList() {
        return userService.queryAllUsers();
    }

    //登录界面Ajax验证
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    //使用shiro登录验证
    public HashMap<String, Object> userLogin(String userName, String password) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            Subject subject = SecurityUtils.getSubject();
            System.out.println("shiro登录验证-----" + userName + password);
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            subject.login(token);
            subject.getSession().setAttribute("user", subject.getPrincipal());
            map.put("resCode", "200");
            map.put("resMsg", "登录成功!");
        } catch (UnknownAccountException e) {
            map.put("resCode", "500");
            map.put("resMsg", "未知账户！");
        } catch (IncorrectCredentialsException e) {
            map.put("resCode", "500");
            map.put("resMsg", "密码错误！");
        } catch (Exception e) {
            map.put("resCode", "500");
            map.put("resMsg", "其他错误！");
        }

        return map;
    }
    /*使用常规方式登录*/
    /*public boolean userLogin(String userName, String password, HttpSession session) {
        System.out.println("userName------" + userName);
        System.out.println("password------" + password);
        String newPassword = SecurityUtil.md5Hex(password);
        System.out.println("加密后的密码是------"+newPassword);
        User user = userService.userLogin(userName);
        if (user == null) {
            return false;
        }
        //如果user不为空，绑定到session中
        session.setAttribute("user", user);
        return true;
    }*/


    //登录成功后进入welcome.jsp
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "welcome";
    }

    //退出登录
//    @ApiIgnore  //隐藏该接口
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login.jsp";
    }
    /*public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/login.jsp";
    }*/


    //用户管理  条件分页
    @ResponseBody
    @ApiOperation(value = "分页查询", notes = "进行分页查询", httpMethod = "GET", produces = "text/html", protocols = "http")
    @RequestMapping(value = "/userList", method = {RequestMethod.GET, RequestMethod.POST})
//    @RequestMapping(value = "/userList")
    public ModelAndView userList(String userName, Integer userRole, Integer pageIndex, Integer pageSize) {
        System.out.println("userName------" + userName);
        System.out.println("userRole------" + userRole);
        System.out.println("pageIndex------" + pageIndex);
        System.out.println("pageSize------" + pageSize);
        ModelAndView modelAndView = new ModelAndView();
        PageUtil<User> pageUtil = new PageUtil<User>();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        List<User> userList = userService.queryAllUsersByCondition(userName, userRole, pageIndex, pageSize);
        List<Role> roleList = roleService.queryAllRoles();
        int totalCount = userService.queryCountByCondition(userName, userRole);
        pageUtil.setPageIndex(pageIndex);
        pageUtil.setPageSize(pageSize);
        pageUtil.setLists(userList);
        pageUtil.setTotalCount(totalCount);
        /*输出pageUtil测试*/
        System.out.println("pageUtil-----" + pageUtil);
        modelAndView.addObject("roleList", roleList);
        modelAndView.addObject("pageUtil", pageUtil);
        modelAndView.setViewName("userList");
        return modelAndView;
    }

    //用户管理 PageHelper分页 vue获取数据
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/userListPageHelperMap", method = {RequestMethod.GET, RequestMethod.POST})
//    @RequestMapping(value = "/userListPageHelper")
    public ResultBaseUtil userListPageHelperMap(String userName, Integer userRole, Integer pageIndex, Integer pageSize) {
//    public Map<String,Object> userListPageHelperMap(String userName, Integer userRole, Integer pageIndex, Integer pageSize) {
        System.out.println("userName = " + userName);
        System.out.println("userRole = " + userRole);
        System.out.println("pageIndex = " + pageIndex);
        System.out.println("pageSize = " + pageSize);
        Map<String, Object> map = new HashMap<>();
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        PageInfo<User> pageInfo = userService.queryAllUsersByPageInfo(userName, userRole, pageIndex, pageSize);

        System.out.println("pageInfo = " + pageInfo);
        map.put("userList", pageInfo.getList());
        map.put("pageInfo", pageInfo);
        map.put("totalCount", pageInfo.getTotal());
        map.put("roleList", roleService.queryAllRoles());
//        return BeanUtil.ok("获得数据成功！",map);
//        return ResultBaseUtil.ok().data("userList",JSON.toJSONString(pageInfo.getList())).data("pageInfo", pageInfo).data("totalCount", pageInfo.getTotal()).data("roleList", roleService.queryAllRoles());
//        return map;
        return ResultBaseUtil.ok("获取用户数据成功！").obj(map);
    }


    //用户管理 PageHelper分页
    @ResponseBody
    @RequestMapping(value = "/userListPageHelper", method = {RequestMethod.GET, RequestMethod.POST})
//    @RequestMapping(value = "/userListPageHelper")
    public ModelAndView userListPageHelper(String userName, Integer userRole, Integer pageNum, Integer pageSize) {
        ModelAndView modelAndView = new ModelAndView();
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        Page<User> page = PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userService.queryAllUsersByPageHelper(userName, userRole);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        System.out.println("pageHelper = " + pageInfo);
        modelAndView.addObject("pageInfo", pageInfo);
        modelAndView.addObject("roleList", roleService.queryAllRoles());
        modelAndView.setViewName("userListPageHelper");
        return modelAndView;
    }

    //用户管理 PageInfo分页
    @ResponseBody
    @RequestMapping(value = "/userListPageInfo", method = {RequestMethod.GET, RequestMethod.POST})
//    @RequestMapping(value = "/userListPageHelper")
    public ModelAndView userListPageInfo(String userName, Integer userRole, Integer pageNum, Integer pageSize) {
        ModelAndView modelAndView = new ModelAndView();
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        System.out.println("pageInfo = " + userService.queryAllUsersByPageInfo(userName, userRole, pageNum, pageSize));
        modelAndView.addObject("pageInfo", userService.queryAllUsersByPageInfo(userName, userRole, pageNum, pageSize));
        modelAndView.addObject("roleList", roleService.queryAllRoles());
        modelAndView.setViewName("userListPageInfo");
        return modelAndView;
    }

    //用户管理  查询所有用户
    @ResponseBody
  /*  @ApiOperation(value = "查询所有用户", notes = "进行全部用户查询", httpMethod = "GET")*/
    @RequestMapping(value = "/userListAll", method = RequestMethod.GET)
    public ModelAndView userListAll() {
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.queryAllUsers();
        List<Role> roleList = roleService.queryAllRoles();
        modelAndView.addObject("roleList", roleList);
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("userListAll");
        return modelAndView;
    }

    //查询用户个人详细信息
 /*   @ApiOperation(notes = "获取单个用户信息", value = "getUserById",
            protocols = "http", produces = "text/html")*/
    @RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView queryUserById(Long id) {
        System.out.println("queryUserById----id----" + id);
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.queryUserById(id);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("userView");
        return modelAndView;
    }

    //删除用户
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/deleteUserById", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultBaseUtil deleteUserById(Long id) {
        System.out.println("进入用户删除方法！要删除的用户的id=" + id);
        int result = userService.deleteUserById(id);
        if (result > 0) {
            return ResultBaseUtil.ok("用户删除成功！");
        } else {
            return ResultBaseUtil.error("用户删除失败！");
        }
    }

    //批量删除用户
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/deleteUsersByList/{ids}", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultBaseUtil deleteUsersByList(@PathVariable("ids") String ids) {
        System.out.println("ids = " + ids);
        //将获得的ids字符串转换成list集合
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        int result = userService.deleteUsersByList(list);
        if (result > 0) {
            return ResultBaseUtil.ok("批量删除用户成功！");
        } else {
            return ResultBaseUtil.error("批量删除用户失败！");
        }
    }

    //加载用户修改界面
    @RequestMapping(value = "/toUserUpdate", method = {RequestMethod.GET, RequestMethod.POST})
    public String toUserUpdate(Long id, Model model) {
        User user = userService.queryUserById(id);
        System.out.println("需要修改的user---" + user);
        model.addAttribute("userUpdate", user);
        List<Role> roleList = roleService.queryAllRoles();
        model.addAttribute("userRoleList", roleList);
        model.addAttribute("userList", JSON.toJSONString(userService.queryAllUsers()));
        return "userUpdate";
    }

    //修改用户信息
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/userUpdate", method = RequestMethod.POST)
    public ResultBaseUtil userUpdate(User user, HttpSession httpSession) {
        User user1 = (User) httpSession.getAttribute("user");
//        user.setModifyBy(user1.getId());
//        String format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
//        user.setModifyDate(new Date());
        System.out.println("修改页面传入的user---" + user);
        //更新登录用户的信息
//        if (user.getId() == user1.getId()) {
//            httpSession.setAttribute("user", user);
//        }
        int result = userService.updateUser(user);
        if (result > 0) {
            return ResultBaseUtil.ok("用户修改成功！");
        } else {
            return ResultBaseUtil.error("用户修改失败！");
        }
    }

    //加载用户新增界面
    @RequestMapping(value = "/toUserAdd", method = RequestMethod.GET)
    public String toUserAdd(Model model) {
        List<Role> roleList = roleService.queryAllRoles();
        model.addAttribute("userRoleList", roleList);
        model.addAttribute("userList", JSON.toJSONString(userService.queryAllUsers()));
        return "userAdd";
    }

    //新增用户
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value = "/userAdd", method = RequestMethod.POST)
    public ResultBaseUtil userAdd(User user, HttpSession session) {
        User user1 = (User) session.getAttribute("user");
        user.setUserPassword(SecurityUtil.md5Hex("111"));
//        user.setCreatedBy(user1.getId());
        user.setCreationDate(new Date());
        System.out.println("新增页面传入的user---" + user);
        int result = userService.addUser(user);
        if (result > 0) {
            return ResultBaseUtil.ok("用户新增成功！");
        } else {
            return ResultBaseUtil.error("用户新增失败！");
        }

    }

    //跳转到密码修改界面
    @RequestMapping(value = "/toPasswordUpdate", method = RequestMethod.GET)
    public String toPasswordUpdate() {
        return "password";
    }

    //修改密码
    @ResponseBody
    @RequestMapping(value = "/passwordUpdate", method = RequestMethod.POST)
    public int passwordUpdate(User user, HttpSession session) {
        user.setUserPassword(SecurityUtil.md5Hex(user.getUserPassword()));
        return userService.updateUser(user);
    }

    //导出
    //将数据库中的数据封装到Excel中，然后下载
    @RequestMapping(value = "/exportUserLists", method = RequestMethod.POST)
    public void downloadUserInfo(HttpServletResponse response) {
        ServletOutputStream servletOutputStream = null;
        String sheetName = "j93";
        List<User> userList = userService.queryAllUsers();
        try {
            servletOutputStream = response.getOutputStream();

            Workbook workbook = ExportExcelUtil.writeNewExcel(sheetName, userList);
            //现在的内容的格式为excel
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //如何处理数据的内容：下载
            response.setHeader("content-disposition", "attachement;fileName=userListExport.xlsx");
            workbook.write(servletOutputStream);

        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                servletOutputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //下载用户Excel模板
    @RequestMapping(value = "/downloadUserDemo", method = RequestMethod.POST)
    public void downloadUserDemo(HttpServletResponse response) {
        String str = "userListDemo.xlsx";
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //获取要下载的文件对象
            File file = ExportExcelUtil.getExcelDemoFile(str);
            //根据文件获取字节数组
            byte[] bytes = FileUtil.readAsByteArray(file);
            //现在的内容的格式为excel
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //如何处理数据的内容：下载
            response.setHeader("content-disposition", "attachement;fileName=userListDemo.xlsx");
            outputStream.write(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //上传用户添加列表导入到数据库中
    @RequestMapping(value = "/uploadUserInfo", method = RequestMethod.POST)
    public String uploadUserInfo(MultipartFile myFile) {
        InputStream inputStream = null;
        try {
            inputStream = myFile.getInputStream();
            //创建指定后缀的文件
            String originalFilename = myFile.getOriginalFilename();
            List<List<Object>> bankListByExcel = ImportExcelUtil.getBankListByExcel(inputStream, originalFilename);
            //遍历 i=1 除去标题
            for (int i = 1; i < bankListByExcel.size(); i++) {
                //获取行
                List<Object> list = bankListByExcel.get(i);
                User user = new User();
                String userCode = (String) list.get(1);
                String userName = (String) list.get(2);
                String gender0 = (String) list.get(3);
                Integer gender = Integer.parseInt(gender0);
                String address = (String) list.get(4);
                user.setUserCode(userCode);
                user.setUserName(userName);
                user.setGender(gender);
                user.setAddress(address);

                userService.addUser(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return "redirect:/user/userList";
    }

    //登录
    @CrossOrigin
    @ResponseBody
    @PostMapping("doLogin")
    public Map<String, Object> doLogin(String userName, String password) {
        HashMap<String, Object> map = new HashMap<>();
        System.out.println("userName = " + userName);
        System.out.println("password = " + password);
        try {
            Subject subject = SecurityUtils.getSubject();
            System.out.println("shiro登录验证-----" + userName + password);
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            subject.login(token);
            subject.getSession().setAttribute("user", (User) subject.getPrincipal());
            User user = (User) subject.getPrincipal();
            map.put("resCode", "200");
            map.put("resMsg", "登录成功!");
            map.put("token", UUID.randomUUID().toString().replace("-", ""));
            map.put("userInfo", user);

        } catch (UnknownAccountException e) {
            map.put("resCode", "500");
            map.put("resMsg", "未知账户！");
        } catch (IncorrectCredentialsException e) {
            map.put("resCode", "500");
            map.put("resMsg", "密码错误！");
        } catch (Exception e) {
            map.put("resCode", "500");
            map.put("resMsg", "其他错误！");
        }

        return map;
    }

}
